package com.cloud.applet.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

/**
 * @Description: SHA-256  哈希算法
 * @ClassName: HashUtil
 * @Date: 2024/9/14 15:35
 * @Version: 1.0     // 版本
 */
public class HashUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String sha256(String phoneNumber) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256", new BouncyCastleProvider());
            byte[] hash = digest.digest(phoneNumber.getBytes(StandardCharsets.UTF_8));
            // Convert byte array into signum representation
            BigInteger number = new BigInteger(1, hash);
            // Convert message digest into hex value
            StringBuilder hexString = new StringBuilder(number.toString(16));
            // Pad with leading zeros
            while (hexString.length() < 64) {
                hexString.insert(0, '0');
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error while hashing", e);
        }
    }

}
